﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Text;
using Maticsoft.DBUtility;
using System.Web.UI;
using System.IO;
using System.Web.Script.Serialization;
using DQYT.HTDZ.Common;
using Newtonsoft.Json;
using System.Collections;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Data.OracleClient;



namespace SkWeb.RiskDB
{
    /// <summary>
    /// Handler 的摘要说明
    /// </summary>
    public class Handler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {

            try
            {
                if (context.Request.QueryString["op"] == "SaveRiskBlockInfo")
                {
                    SaveRiskBlockInfo(context);
                    context.Response.Write("保存成功！");
                }
                else if (context.Request.QueryString["op"] == "queryrisk")
                {
                    queryRisk(context);
                }
                else if (context.Request.QueryString["op"] == "identification")
                {
                    getRank();
                }
                else if (context.Request.QueryString["op"] == "getall")
                {
                    ReturnAll(context);
                }
                else if (context.Request.QueryString["op"] == "delete")//删除风险区块信息
                {
                    string strId = context.Request.Form["id"];//passModel.ObjID = long.Parse(Request.Form["objid"]);
                    string strSql = "delete from tb_riskblockinfo where id ="+strId;
                    if (DbHelperOra.ExecuteSql(strSql) == 1)
                    {
                        context.Response.Write("删除成功！");
                    }
                    else
                    {
                        context.Response.Write("删除失败！");
                    }

                }
                else if (context.Request.QueryString["op"] == "update")//更新风险区块信息
                {
                    string strId = context.Request.Form["id"];//passModel.ObjID = long.Parse(Request.Form["objid"]);
                    string strFx = context.Request.Form["fx"];
                    string strDes = context.Request.Form["des"];
                    string strSql = "update  tb_riskblockinfo set rank="+strFx+",des='"+strDes+"' where id =" + strId;
                    if (DbHelperOra.ExecuteSql(strSql) == 1)
                    {
                        context.Response.Write("修改成功！");
                    }
                    else
                    {
                        context.Response.Write("修改失败！");
                    }

                }
                else
                {
                    ReturnRiskDBInfo(context);
                }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
        }

        public void queryRisk(HttpContext context)
        {
            string strName = context.Request.Form["name"];
            //string strSql = "select * from  tb_exception_info where jh='"+strName+"'";
            //DataTable dt = DbHelperOra.Query(strSql).Tables[0];
            //if (dt.Rows.Count > 0)
            //{
            //    context.Response.Write("这口井存在于历史风险数据库中，请注意！");
            //    context.Response.End();
            //    return;
            //}
            //else
            {

               string   strSql = "select rank from  tb_wellinfo where name='" + strName + "'";
               DataTable  dt = DbHelperOra.Query(strSql).Tables[0];
                string message="";
                if (dt.Rows.Count > 0)
                {
                    if (dt.Rows[0][0].ToString() == "1")
                    {
                        message = "这口井为一级风险井，请注意";
                    }
                    else if (dt.Rows[0][0].ToString() == "2")
                    {
                        message = "这口井为二级风险井，请注意";
                    }
                    else if (dt.Rows[0][0].ToString() == "3")
                    {
                        message = "这口井为三级风险井，请注意";
                    }
                    else if (dt.Rows[0][0].ToString() == "-1")
                    {
                        message = "风险级别尚未检测";
                    }
                    else if (dt.Rows[0][0].ToString() == "0")
                    {
                        message = "这口井没有风险";
                    }
                    context.Response.Write(message);
                    context.Response.End();
                    return;
                }
                context.Response.Write("未检测到风险信息");
                context.Response.End();
                return;

            }

        }


        /// <summary>
        /// 返回所有风险区块信息
        /// </summary>
        /// <param name="context"></param>
        private void ReturnAll(HttpContext context)
        {
            string strSql = "select ID,DATA,RANK,TYPE,DES from tb_riskblockinfo";
            DataTable dt = DbHelperOra.Query(strSql).Tables[0];

            string json = JsonHelper.ToJson(dt);

            context.Response.ContentType = "text/json";
            context.Response.Write(json);
            context.Response.End();

        }

      
        /// <summary>
        /// 暂时未被用上
        /// </summary>
        /// <param name="context"></param>
        private void ReturnRiskDBInfo(HttpContext context)
        {

            string resultJson = string.Empty;
            string strTableName = context.Request.QueryString["name"];

            string strSql = "select table_name,column_name, to_char( data_type) type,  '('||data_precision ||','||data_scale||')' pre_scale from user_tab_columns where table_name='" + strTableName + "'";

            DataTable dt = DbHelperOra.Query(strSql).Tables[0];

            StringBuilder resultBuilder = new StringBuilder("{\"rows\":[");
            string jsonFormat = "{{\"id\": {0},\"Name\": \"{1}\", \"Type\": \"{2}\",\"Precision\": \"{3}\", \"Start\": \"{4}\",\"End\": \"{5}\",\"Level\": \"{6}\",\"Describe\": \"{7}\"}},";
            string jsonFormatChild = "{{\"id\": {0},\"Name\": \"{1}\", \"Type\": \"{2}\",\"Precision\": \"{3}\", \"Start\": \"{4}\",\"End\": \"{5}\",\"Level\": \"{6}\",\"Describe\": \"{7}\",\"_parentId\": {8}}},";
            if (dt != null && dt.Rows.Count > 0)
            {
                int i = 0;
                string strPrecisioin = "";
                foreach (var row in dt.AsEnumerable())
                {
                    strPrecisioin = "";
                    if (row["type"].ToString() == "NUMBER")
                        strPrecisioin = row["pre_scale"].ToString();
                    resultBuilder.AppendFormat(jsonFormat, (++i).ToString(), row["column_name"].ToString(), row["type"].ToString(), strPrecisioin, " ", " ", " ", " ", " ");
                }
            }

            ////附加风险数据库
            strSql = "select * from risk_table where tname='" + strTableName + "' ";
            DataTable dtRisk = DbHelperOra.Query(strSql).Tables[0];
            if (dtRisk != null && dtRisk.Rows.Count > 0)
            {
                int i = 1;
                int s = 1000;
                foreach (var row in dt.AsEnumerable())
                {
                    string col_name = row["column_name"].ToString().ToUpper();
                    foreach (var row_ in dtRisk.AsEnumerable())
                    {
                        if (row_["CNAME"].ToString().ToUpper() == col_name)
                            resultBuilder.AppendFormat(jsonFormatChild, (s++).ToString(), row_["DESCRIBE"].ToString(), "",
                                "", row_["VSTART"].ToString(), row_["VEND"].ToString(), row_["NLEVEL"].ToString(), "", i.ToString());
                    }
                    i++;
                }
            }

            if (resultBuilder.Length > 1)
            {
                resultBuilder = resultBuilder.Remove(resultBuilder.Length - 1, 1);
            }

            resultBuilder.Append("]}");
            resultJson = resultBuilder.ToString();

            context.Response.ContentType = "text/json";

            context.Response.Write(resultJson);

        }

        private void getRank()
        {
            try
            {
                List<Region> regions = new List<Region>();
                List<int> ranks = new List<int>();
                List<int> ids = new List<int>();

                DataTable dt = DbHelperOra.Query("select id, data,rank,type from tb_riskblockinfo").Tables[0];
                foreach (DataRow dr in dt.Rows)
                {
                    GraphicsPath myGraphicsPath = new GraphicsPath();
                    Region myRegion = new Region();
                    myGraphicsPath.Reset();
                    string strData = dr["data"].ToString();
                    if (dr["type"].ToString() == "polygon")
                    {
                        string[] data = strData.Split(',');
                        List<Point> points = new List<Point>();
                        for (int i = 0; i < data.Length-1; i += 2)
                        {
                            Point point = new Point((int)(Convert.ToSingle(data[i]) * 100000), (int)(Convert.ToSingle(data[i + 1]) * 100000));
                            points.Add(point);
                        }
                        myGraphicsPath.AddPolygon(points.ToArray());
                    }
                    else if (dr["type"].ToString() == "circle")
                    {
                    }
                    else if (dr["type"].ToString() == "poly")
                    {
                    }
                    myRegion.MakeEmpty();
                    myRegion.Union(myGraphicsPath);
                    regions.Add(myRegion);
                    ranks.Add(Convert.ToInt32(dr["rank"].ToString()));
                    ids.Add(Convert.ToInt32(dr["id"].ToString()));
                }

                string strSql = "select id,name, lng,lat,rank from tb_wellinfo";
                ArrayList sqls = new ArrayList();
                DataTable dtWellInfo = DbHelperOra.Query(strSql).Tables[0];
                foreach (DataRow dr in dtWellInfo.Rows)
                {
                    Point wellPos = new Point((int)(Convert.ToSingle(dr["lng"]) * 100000), (int)(Convert.ToSingle(dr["lat"]) * 100000));
                    int i = 0;
                    for (i = 0; i < regions.Count; i++)
                    {
                        if (regions[i].IsVisible(wellPos))
                        {
                            strSql = "update tb_wellinfo set block_id= " + ids[i].ToString() + ", rank =" + ranks[i].ToString() + " where id= " + dr["id"].ToString();
                            sqls.Add(strSql);
                            break;
                        }
                    }
                    if (i == regions.Count)
                    {
                        strSql = "update tb_wellinfo set block_id= -1, rank =0 where id= " + dr["id"].ToString();
                        sqls.Add(strSql);
                    }

                }
                DbHelperOra.ExecuteSqlTran(sqls);
                
                
            }
            catch (Exception ex)
            {

            }
            // return rank;
        }

        private void SaveRiskBlockInfo(HttpContext context)
        {
            var jsonString = String.Empty;
            //context.Request.InputStream.Position = 0;
            //using (var inputStream = new StreamReader(context.Request.InputStream))
            //{
            //    jsonString = inputStream.ReadToEnd();
            //}
            jsonString = context.Request.Form["data"];
            ArrayList sqlList = new ArrayList();
            JavaScriptArray jArr = (JavaScriptArray)JavaScriptConvert.DeserializeObject(jsonString);

            if (jArr.Count > 0)
            {
                Newtonsoft.Json.JavaScriptObject jObj = (Newtonsoft.Json.JavaScriptObject)(jArr[0]);
                Dictionary<string, object> jDic = (Dictionary<string, object>)jObj;
                string strType = jDic["type"].ToString();
                string strRank = jDic["rank"].ToString();
                string strDesc = jDic["desc"].ToString();
                string strData = "";
                if (strType == "polygon")
                {
                    JavaScriptArray jArr1 = (JavaScriptArray)jDic["data"];
                    strData = analyze_polygon(jArr1);
                }
                string strSql = "insert into tb_RiskBlockInfo(data,rank,type,des) values('" + strData + "'," + strRank + ",'" + strType + "','"+strDesc+"')";
                if (DbHelperOra.ExecuteSql(strSql) == 1)
                {
                    int id = DbHelperOra.GetMaxID("id", "tb_RiskBlockInfo")-1;
                    context.Response.Write(id.ToString());
                    context.Response.End();
                }
            }

        }


        private string analyze_polygon(JavaScriptArray jArrData)
        {
            string strData = "";
            for (int i = 0; i < jArrData.Count; i++)
            {
                Dictionary<string, object> jDic1 = (Dictionary<string, object>)jArrData[i];
                object lng_value = jDic1["lng"];
                object lat_value = jDic1["lat"];
                strData += lng_value.ToString() + "," + lat_value + ",";
            }
            if (strData.Length > 1)
            {
                strData = strData.Remove(strData.Length - 1);
            }
            return strData;
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }


    }
}